import { Buffer } from 'buffer';

// 密钥派生函数
async function deriveKey(password: string, salt: Uint8Array): Promise<CryptoKey> {
  const encoder = new TextEncoder();
  const keyMaterial = await window.crypto.subtle.importKey(
    'raw',
    encoder.encode(password),
    { name: 'PBKDF2' },
    false,
    ['deriveBits', 'deriveKey']
  );

  return window.crypto.subtle.deriveKey(
    {
      name: 'PBKDF2',
      salt: salt,
      iterations: 10000,
      hash: 'SHA-512'
    },
    keyMaterial,
    { name: 'AES-CBC', length: 256 },
    false,
    ['decrypt']
  );
}

// 解密函数
export async function decrypt(encryptedText: string, password: string): Promise<string> {
  try {
    // 解码Base64字符串
    const encryptedData = Buffer.from(encryptedText, 'base64');

    // 提取salt和IV
    const salt = encryptedData.slice(0, 16);
    const iv = encryptedData.slice(16, 32);
    const ciphertext = encryptedData.slice(32);

    // 派生密钥
    const key = await deriveKey(password, salt);

    // 解密
    const decrypted = await window.crypto.subtle.decrypt(
      {
        name: 'AES-CBC',
        iv: iv
      },
      key,
      ciphertext
    );

    // 将解密后的数据转换为字符串
    return new TextDecoder().decode(decrypted);
  } catch (error) {
    console.error('解密失败:', error);
    throw new Error('解密失败');
  }
}

// 使用示例
export async function decryptJasypt(encryptedValue: string): Promise<string> {
  const password = 'EbfYkitulv73I2p0mXI50JMXoaxZTKJ7';
  return decrypt(encryptedValue, password);
}